package com.bjc.controller;

import com.bjc.config.TransactionUtils;
import com.bjc.pojo.Student;
import com.bjc.pojo.User;
import com.bjc.service.StudentService;
import com.bjc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @program: ssmpractice
 * @description:
 * @author: bjc
 * @create: 2020-08-30 19:34
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TransactionUtils tranManager;

    @GetMapping(value = "/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list",userService.findAll());
        return modelAndView;
    }

    @GetMapping(value = "/add")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("add");
        User user = new User();
        user.setId(21l);
        user.setName("李四");
        user.setAge(21);

        Student student = new Student();
        student.setId(4);
        student.setName("赵六六");
        student.setCid("1");

        //开启事务
//        TransactionStatus begin = tranManager.begin();
//        try {
//            userService.add(user);
//            int a = 1/0;
//            studentService.addStudent(student);
//        }catch (Exception e){
//            //异常回滚
//            tranManager.rollback(begin);
//        }finally {
//            //正常执行，提交事务
//            tranManager.commit(begin);
//        }

        userService.add(user);
        int a = 1/0;
        studentService.addStudent(student);

        return modelAndView;
    }
}
